package com.huirui.server.controller.admin;

import com.huirui.server.constant.OrderStatus;
import com.huirui.server.exception.OrderNotExistsException;
import com.huirui.server.pojo.dto.ConfirmShipmentDto;
import com.huirui.server.pojo.entity.Order;
import com.huirui.server.pojo.result.PageResult;
import com.huirui.server.pojo.result.Result;
import com.huirui.server.pojo.vo.DeliveryInformationVo;
import com.huirui.server.pojo.vo.HighlyDetailedOrderDetailVo;
import com.huirui.server.pojo.vo.OrderCountVo;
import com.huirui.server.pojo.vo.OrderVo;
import com.huirui.server.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;

@RestController("adminOrderController")
@RequestMapping("/admin/order")
@Slf4j
@Validated
@Tag(name = "订单管理", description = "小程序订单管理")
public class OrderController {
    @Resource
    private OrderService orderService;

    @RequestMapping(method = RequestMethod.GET, value = "/list")
    @Operation(summary = "查询订单列表")
    public Result<PageResult<OrderVo>> listOrderVo(
            @RequestParam(required = false) @Parameter(description = "订单类型，0-普通订单，1-秒杀订单") Integer orderType,
            @RequestParam(required = false) @Parameter(description = "支付方式，0-微信支付，1-余额支付") Integer paymentMethod,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") @Parameter(description = "订单开始时间") LocalDate beginTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") @Parameter(description = "订单结束时间") LocalDate endTime,
            @RequestParam(required = false) @Parameter(description = "查询条件。0-订单编号，1-用户昵称，2-用户ID，3-收货人姓名，4-收货人手机号，5-产品名称") Integer searchCondition,
            @RequestParam(required = false) @Parameter(description = "查询值") String searchValue,
            @RequestParam(required = false) @Parameter(description = "订单状态：0-待付款，1-待发货，2-待收货，3-已完成，4-已取消，5-售后") Long status,
            @RequestParam("currentPage") @Min(value = 1, message = "页码不能小于1") @Parameter(description = "查询页码") Integer currentPage,
            @RequestParam("pageSize") @Min(value = 1, message = "每页条数不能小于1") @Parameter(description = "页面大小") Integer pageSize
    ) {
        PageResult<OrderVo> res = orderService.listOrderVo(orderType, paymentMethod, status, beginTime, endTime, searchCondition, searchValue, currentPage, pageSize);
        return Result.success(res);
    }

    @GetMapping("/count")
    @Operation(summary = "获取待发货和待付款的订单数量")
    public Result<OrderCountVo> getBriefOrderCount() {
        OrderCountVo orderCountVo = orderService.getBriefOrderCount();
        return Result.success(orderCountVo);
    }


    @PatchMapping("/merchantNote")
    @Operation(summary = "编辑商家备注")
    public Result<Void> editMerchantNote(@RequestBody Map<String, Object> params) {
        Long orderId = Long.valueOf(params.get("orderId").toString());
        String merchantNote = (String) params.get("merchantNote");
        orderService.editMerchantNote(orderId, merchantNote);
        return Result.success();
    }

    @PatchMapping("/editOrderPrice")
    @Operation(summary = "编辑订单价格")
    public Result<Void> editOrderPrice(@RequestBody Map<String, Object> params) {
        Long orderId = Long.valueOf(params.get("orderId").toString());
        String actualPayment = (String) params.get("actualPayment");
        orderService.editOrderPrice(orderId, actualPayment);
        return Result.success();
    }

    @PatchMapping("/close/{orderId}")
    @Operation(summary = "关闭订单")
    public Result<Void> closeOrder(@PathVariable("orderId") Long orderId) {
        orderService.closeOrder(orderId);
        return Result.success();
    }


    @GetMapping("/detail")
    @Operation(summary = "获取订单详情信息")
    public Result<HighlyDetailedOrderDetailVo> getOrderDetail(@RequestParam("orderId") Long orderId) {
        HighlyDetailedOrderDetailVo orderDetailVo = orderService.getHighlyDetailedOrderDetails(orderId);
        return Result.success(orderDetailVo);
    }


    @PatchMapping("/confirm/payment")
    @Operation(summary = "确定付款")
    public Result<Void> confirmThePayment(@RequestParam("orderId") Long orderId) {
        boolean exists = orderService
                .lambdaQuery()
                .eq(Order::getId, orderId)
                .exists();
        if (!exists) {
            throw new OrderNotExistsException("订单不存在~！");
        }
        orderService
                .lambdaUpdate()
                .eq(Order::getId, orderId)
                .set(Order::getStatus, OrderStatus.PENDING_DELIVERY)
                .set(Order::getPayTime, LocalDateTime.now())
                .update();
        return Result.success();
    }

    @PatchMapping("/confirm/shipment")
    @Operation(summary = "确定发货")
    public Result<Void> confirmShipment(@Valid @RequestBody ConfirmShipmentDto confirmShipmentDto) {
        orderService.confirmShipment(confirmShipmentDto);
        return Result.success();
    }

    @PatchMapping("/confirm/receipt")
    @Operation(summary = "确认收货")
    public Result<Void> confirmReceipt(@RequestParam("orderId") Long orderId) {
        orderService.confirmReceipt(orderId);
        return Result.success();
    }


    @GetMapping("/delivery/information")
    @Operation(summary = "获取配送信息")
    public Result<DeliveryInformationVo> getDeliveryInformation(@RequestParam Long orderId) {
        DeliveryInformationVo deliveryInformationVo = orderService.getDeliveryInformation(orderId);
        return Result.success(deliveryInformationVo);
    }

    @PatchMapping("/update/delivery/information")
    @Operation(summary = "修改配送信息")
    public Result<Void> modifyDeliveryInformation(@Valid @RequestBody ConfirmShipmentDto confirmShipmentDto) {
        orderService.modifyDeliveryInformation(confirmShipmentDto);
        return Result.success();
    }


}
